package com.google.code.alpaca.prototype.server;

import java.lang.reflect.Constructor;

import com.google.code.alpaca.prototype.dao.DAOMapping;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;

public class DAOProvider<T> implements Provider<T> {
	private static DAOMapping mapping;
	private static Injector injector;

	private Class<T> daoType;

	DAOProvider(Class<T> cls) {
		this.daoType = cls;
	}

	@Inject
	public static void init(DAOMapping aMapping, Injector aInjector) {
		mapping = aMapping;
		injector = aInjector;
	}

	@Override
	public T get() {
		return createDAO(mapping, injector, daoType);
	}

	private static <T> T createDAO(DAOMapping mapping, Injector injector,
			Class<T> daoClass) {
		@SuppressWarnings("unchecked")
		Class<T> type = (Class<T>) mapping.getImplementationType(daoClass);
		T dao;
		try {
			Constructor<T> con = type.getDeclaredConstructor();
			con.setAccessible(true);
			dao = con.newInstance();
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
		injector.injectMembers(dao);
		return dao;
	}

}